package com.zhike.service.group.impl;

import java.time.Instant;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.zhike.common.dto.GroupMember4Cache;
import com.zhike.common.enums.YesNoEnum;
import com.zhike.common.model.GroupMembers;
import com.zhike.mapper.group.GroupMemberMapper;
import com.zhike.service.group.IGroupMemberService;

@Service
public class GroupMemberServiceImpl implements IGroupMemberService {

  @Resource
  private GroupMemberMapper groupMemeberMapper;

  @Override
  public List<GroupMember4Cache> queryGroupMemberList(String gid) {
    // 群员列表数据库行数据
    return groupMemeberMapper.selectGroupMemberInfoList(gid);
  }

  public GroupMembers selectGroupMemberInfo(String groupId, String userId) {
    LambdaQueryWrapper<GroupMembers> lqw = new LambdaQueryWrapper<>();
    lqw.eq(GroupMembers::getGId, groupId);
    lqw.eq(GroupMembers::getUserUid, userId);
    return groupMemeberMapper.selectOne(lqw);
  }

  @Override
  public Boolean checkGroupAdmin(String groupId, String userId) {
    return groupMemeberMapper.selectMemberAdmin(groupId, userId) > 0;
  }

  @Override
  public Boolean prohibitMember(String groupId, String userId, Integer action, Integer interval) {
    LambdaUpdateWrapper<GroupMembers> luw = new LambdaUpdateWrapper<>();
    luw.eq(GroupMembers::getGId, groupId);
    luw.eq(GroupMembers::getUserUid, userId);
    luw.set(GroupMembers::getProhibitMsg, action);
    // 禁言
    if (action.equals(YesNoEnum.YES.getValue())) {
      Instant instant = Instant.now();
      if (interval == -1) { // 永久
        luw.set(GroupMembers::getMsgTimeStart, 0);
        luw.set(GroupMembers::getMsgTimeEnd, -1);
      } else if (interval > 0) {
        long currentTimeMillis = instant.toEpochMilli();
        luw.set(GroupMembers::getMsgTimeStart, currentTimeMillis);
        luw.set(GroupMembers::getMsgTimeEnd, currentTimeMillis + interval * 1000);
      }
    } else if (action.equals(YesNoEnum.NO.getValue()) || action.equals(-1)) { // 解除
      luw.set(GroupMembers::getMsgTimeStart, 0);
      luw.set(GroupMembers::getMsgTimeEnd, 0);
    }

    return groupMemeberMapper.update(new GroupMembers(), luw) > 0;
  }

}
